package com.example.home.vm

import android.util.Log
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.common.entity.CommendEntity
import com.example.common.entity.CommendReply
import com.example.common.vm.BaseViewModel
import com.example.home.intent.HomeViewIntent
import com.example.home.repo.HomeRepository
import com.example.home.state.HomeUiState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okio.ProtocolException
import javax.inject.Inject

/**
 * StateFlow和SharedFlow的区别
 * 1.是否需要设置默认值,StateFlow必须设置默认值,SharedFlow不需要设置默认值
 * 2.是否接收相同的值:StateFlow不能,SharedFlow可以接收相同的状态
 * 3.是否存在缓存:StateFlow存在缓存,SharedFlow不存在缓存
 * 4.是否可以多次订阅接收数据,StateFlow不可以,SharedFlow可以
 */
@HiltViewModel
class HomeViewModel:BaseViewModel<HomeViewIntent>() {

    private val repository: HomeRepository = HomeRepository()


//    //可变,防止外部修改StateFlow
//    private val _uiStateFlow = MutableStateFlow<HomeUiState>(HomeUiState.LoadEmpty)
//    //对外去暴露StateFlow用于收集数据
//    val uiStateFlow :StateFlow<HomeUiState> = _uiStateFlow.asStateFlow()
//可变,防止外部修改StateFlow
private val _uiStateFlow = MutableSharedFlow<HomeUiState>()
    //对外去暴露StateFlow用于收集数据
    val uiStateFlow : SharedFlow<HomeUiState> = _uiStateFlow.asSharedFlow()

    //分发View层的意图
    override fun dispatchIntent(intent: HomeViewIntent) {
        when(intent){
            is HomeViewIntent.LoadVideType->loadSimpleType()
            is HomeViewIntent.LoadSimpleVideoListById -> loadSimpleVideoByChannelId(intent.channelId, intent.page, intent.pageSize)
            is HomeViewIntent.LoadRecommendSimpleVideoList -> loadRecommendVideo(intent.pageIndex, intent.pageSize)
            is HomeViewIntent.LoadVideoCommendList -> loadVideoCommendList(intent.dataType, intent.itemId)
            is HomeViewIntent.PublishVideoComment -> publishVideoComment(intent.entity)
        }
    }
    //模拟评论回复数据
    private var mockReplayComment = listOf(
        CommendReply(0, 0, "我来了", "2023-12-20 14:23:21", 0, "芝士雪豹", 0, 1, "https://ww2.sinaimg.cn/mw690/005Zk4Aqgy1hqcerik29rj30u012w76n.jpg" ),
        CommendReply(0, 0, "假的真不了", "2023-12-20 14:23:23", 1, "虾仁不眨眼", 0, 1, "https://wx4.sinaimg.cn/mw690/006faMndly1hqns4dao43j30u0140401.jpg" ),
        CommendReply(0, 0, "言之有理", "2023-12-20 14:23:25", 2, "熊猫很困", 0, 1, "https://wx1.sinaimg.cn/mw690/005OayIHly1hqdnyvre3zj30w70w7do8.jpg" ),
        CommendReply(0, 0, "我觉得太假了，一点儿不真实！！", "2023-12-20 14:23:26", 3, "鱼香 rose", 0, 1, "https://q9.itc.cn/q_70/images03/20240829/e9b4ccc3579f4787976d3458229fe1a1.jpeg" ),
        CommendReply(0, 0, "啥也不是！！", "2023-12-20 14:23:26", 4, "吃土少女", 0, 1, "https://img1.baidu.com/it/u=3254750559,1502332285&fm=253&fmt=auto&app=120&f=GIF?w=285&h=285" ),
        CommendReply(0, 0, "太傻了！！", "2023-12-20 14:23:26", 5, "摆烂小柯基", 0, 1, "https://p1-dy.bytexservice.com/img/user-avatar/d71e237251a88a91222c30a4dc3bf9e6~300x300.image" ),
        CommendReply(0, 0, "我觉得太假了，一点儿不真实！！", "2023-12-20 14:23:26", 6, "摸鱼喵星人", 0, 1, "https://p1-dy.bytexservice.com/img/user-avatar/d71e237251a88a91222c30a4dc3bf9e6~300x300.image" ),
        CommendReply(0, 0, "给你点赞！！", "2023-12-20 14:23:26", 7, "睡不醒的猪", 0, 1, "https://p1-dy.bytexservice.com/img/user-avatar/d71e237251a88a91222c30a4dc3bf9e6~300x300.image" ),
        CommendReply(0, 0, "努力加油！！", "2023-12-20 14:23:26", 8, "暴躁小松鼠", 0, 1, "https://img1.baidu.com/it/u=3053515689,4170843785&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500" ),
        CommendReply(0, 0, "我觉得太假了，一点儿不真实！！", "2023-12-20 14:23:26", 9, "干饭小仓鼠", 0, 1, "https://img1.baidu.com/it/u=3053515689,4170843785&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500" ),
        CommendReply(0, 0, "加油！！", "2023-12-20 14:23:26", 10, "减肥版干饭王", 0, 1, "https://q9.itc.cn/q_70/images03/20240829/e9b4ccc3579f4787976d3458229fe1a1.jpeg" ),
        CommendReply(0, 0, "一点儿不真实！！", "2023-12-20 14:23:26", 11, "外卖依赖症", 0, 1, "" ),
        CommendReply(0, 0, "牛逼牛逼，太漂亮了！！", "2023-12-20 14:23:26", 12, "气泡音小笨蛋", 0, 1, "https://img0.baidu.com/it/u=306649616,2230355986&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500" ),
    )

    private fun loadSimpleType() {
        mViewModelScope.launch (mDispatcher){
            //发送请求并收集数据
            repository.getSimpleType().collect{list->
                if (list.isNotEmpty()){
                    _uiStateFlow.emit(HomeUiState.LoadSimpleTypeSuccess(list))
                }else{
                 _uiStateFlow.emit( HomeUiState.LoadSimpleTypeFail("没有获取到视频分类!"))
                }
            }
        }
    }

    private fun loadRecommendVideo(pageIndex: Int, pageSize: Int) {
        mViewModelScope.launch(mDispatcher) {
            repository.getRecommendSimpleVideoList(pageIndex, pageSize).collect{ list ->
                if (list.isNotEmpty()){
                    _uiStateFlow.emit(HomeUiState.LoadSimpleVideoSuccess(list))
                } else {
                    _uiStateFlow.emit(HomeUiState.LoadSimpleVideoFail("没有获取到推荐视频！"))
                }
            }
        }
    }

    private fun loadSimpleVideoByChannelId(channelId: String, page: Int, pageSize: Int){
        mViewModelScope.launch(mDispatcher) {
            repository.getSimpleVideoList(channelId, page, pageSize).collect{ list ->
                if (list.isNotEmpty()){
                    _uiStateFlow.emit(HomeUiState.LoadSimpleVideoSuccess(list))
                } else {
                    _uiStateFlow.emit( HomeUiState.LoadSimpleVideoFail("没有获取到分类视频！"))
                }
            }
        }
    }

    private fun loadVideoCommendList(dataType: Int, itemId: String){
        mViewModelScope.launch(mDispatcher) {
            repository.getVideoCommends(dataType, itemId).collect{ list ->
                if (list.isNotEmpty()){
                    list.forEach {
                        randomConfigReplayComment(it)
                    }
                    _uiStateFlow.emit( HomeUiState.LoadVideoCommendSuccess(list))
                } else {
                   _uiStateFlow.emit(HomeUiState.LoadVideoCommendFail("没有获取到视频评论！"))
                }
            }
        }
    }

    private fun publishVideoComment(commendEntity: CommendEntity){
        mViewModelScope.launch(mDispatcher) {
            try {
                // 封装Body参数
                val requestBody: RequestBody = GsonUtils.toJson(commendEntity).toRequestBody("application/json;charset=utf-8".toMediaTypeOrNull())
                repository.publishVideoComment(requestBody).collect { list ->
                    ToastUtils.showLong("发送评论成功")
                    loadVideoCommendList(list.datatype, list.itemid.toString())
                }
            } catch (e: ProtocolException) {
                Log.e("PublishCommentError", "服务器返回非法HTTP状态码", e)
                _uiStateFlow.emit(HomeUiState.LoadVideoCommendFail(msg = "发布评论失败：服务器响应格式错误"))
            } catch (e: Exception) {
                Log.e("PublishCommentError", "发布评论异常", e)
                _uiStateFlow.emit(HomeUiState.LoadVideoCommendFail(msg = "发布评论异常：${e.message}"))
            }
        }
    }

    /**
     * 随机模拟评论回复
     */
    private fun randomConfigReplayComment(entity: CommendEntity){
        //设置头像
        entity.userlogo = "https://q3.itc.cn/q_70/images03/20250110/1e71eecf56b34344bcae6a5b85c0bec2.jpeg"
        var randomNum = (Math.random() * 10 + 1).toInt()
        entity.replytotal = randomNum
        //二级评论
        while (randomNum > 0){
            val fromIndex = (mockReplayComment.size - 2) % ((Math.random() * 10).toInt() + 1)
            entity.replyList.addAll(mockReplayComment.subList(fromIndex, fromIndex + 1))
            randomNum -=1
        }
    }

}
